﻿using System;
using System.Data.Objects;
using System.Linq;
using NopSolutions.NopCommerce.BusinessLogic.Data;
using NopSolutions.NopCommerce.BusinessLogic.Model;

namespace NopSolutions.NopCommerce.BusinessLogic.Services
{
    public static class TopicCompiledQueries
    {
        public static readonly Func<NopObjectContext, IQueryable<Topic>> Topics =
            CompiledQuery.Compile<NopObjectContext, IQueryable<Topic>>(
                    (ctx) =>
                        from t in ctx.Topics
                        select t
            );

        public static readonly Func<NopObjectContext, int, Topic> TopicById =
            CompiledQuery.Compile<NopObjectContext, int, Topic>(
                    (ctx, id) =>
                        (from t in ctx.Topics
                         where t.TopicId == id
                         select t).FirstOrDefault()
            );

        public static readonly Func<NopObjectContext, int, LocalizedTopic> LocalizedTopicById =
            CompiledQuery.Compile<NopObjectContext, int, LocalizedTopic>(
                    (ctx, id) =>
                        (from t in ctx.LocalizedTopics
                         where t.TopicLocalizedId == id
                         select t).FirstOrDefault()
            );

        public static readonly Func<NopObjectContext, int, int, LocalizedTopic> LocalizedTopicByTopicAndLanguage =
            CompiledQuery.Compile<NopObjectContext, int, int, LocalizedTopic>(
                    (ctx, topicId, languageId) =>
                        (from t in ctx.LocalizedTopics
                         where
                            t.TopicId == topicId &&
                            t.LanguageId == languageId
                         select t).FirstOrDefault()
            );

        public static readonly Func<NopObjectContext, string, int, LocalizedTopic> LocalizedTopicByTopicNameAndLanguageId =
            CompiledQuery.Compile<NopObjectContext, string, int, LocalizedTopic>(
                    (ctx, topicName, languageId) => (from tl in ctx.LocalizedTopics
                                                     join t in ctx.Topics on tl.TopicId equals t.TopicId
                                                     where tl.LanguageId == languageId &&
                                                     t.Name == topicName
                                                     select tl).FirstOrDefault()
            );
    }
}
